/* eslint-disable no-script-url */
/* eslint-disable react/jsx-indent */
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable import/order */
/* eslint-disable array-callback-return */
// 客户模糊查询
import React, { PureComponent } from 'react';
import { DownOutlined, UpOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Button, Col, Input, Divider, Dropdown, Menu, message, Modal, Badge } from 'antd';
import StandardTable from '@/components/StandardTable';
import { connect } from 'dva';
import router from 'umi/router';
import Area from '../../components/Area';
import Authorized from '@/utils/Authorized';
import DictCode from '../../components/DictCode';
import styles from '@/utils/utils.less';
import BigwareList from './Bigwarelist';
import { checkPermissions } from '@/utils/authority';

const { confirm } = Modal;
const FormItem = Form.Item;
@connect(({ accuware, bigaccomanage, loading }) => ({
  loading: loading.effects['accuware/fetchAccuList'],
  listLoading: loading.effects['accuware/fetchBigwareList'],
  tabList: accuware.tabList,
  activeKey: accuware.activeKey,
  pageData: accuware.pageData,
  formFieldsValue: accuware.formFieldsValue,
  expandForm: accuware.expandForm,
  bigwareList: accuware.bigwareList,
  selectedRowKeys: bigaccomanage.selectedRowKeys,
  selectedRows: bigaccomanage.selectedRows,
}))
@Form.create()
class AccuWare extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      stateMap: ['', 'default', 'success', 'warning'],
    };
    this.formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
  }

  componentDidMount = () => {
    const {
      pageData: { pagination },
      location: {
        query: { isMenuLink },
      },
      location,
    } = this.props;
    if (isMenuLink === 'true') {
      this.resetAndGeLlist(location);
    } else {
      this.getList(pagination.current, pagination.pageSize);
    }
  };

  // 切换
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'accuware/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  // 重置
  resetSearch = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'accuware/updateModelData',
      payload: { formFieldsValue: {} },
    });
    form.resetFields();
  };

  getList = (currentPage = 1, pageSize = 10) => {
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      dispatch({
        type: 'accuware/fetchAccuList',
        payload: {
          unitName: fieldsValue.accuUnitName && fieldsValue.accuUnitName.trim(),
          accuAccoId: fieldsValue.accuAccoId && fieldsValue.accuAccoId.trim(),
          areaId: fieldsValue.accuAreaId && fieldsValue.accuAreaId.key,
          accoStatus: fieldsValue.accoStatus && fieldsValue.accoStatus.trim(),
          pageArg: {
            currentPage,
            pageSize,
          },
        },
      });
      dispatch({
        type: 'accuware/updateModelData',
        payload: { formFieldsValue: fieldsValue },
      });
    });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize);
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'bigaccomanage/updateModelData',
      payload: { selectedRowKeys, selectedRows },
    });
  };

  deleteItem = () => {
    // eslint-disable-next-line no-underscore-dangl
    const { selectedRowKeys, dispatch } = this.props;
    if (!selectedRowKeys.length) {
      message.warning('至少选择一条数据');
      return;
    }
    confirm({
      title: '你确定要删除此大库信息吗？',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk() {
        dispatch({
          type: 'accuware/deleteAccuMul',
          payload: { list: selectedRowKeys },
        });
      },
      onCancel: () => {},
    });
  };

  // - 新增
  invoiceApply = () => {
    const {
      location: { pathname },
    } = this.props;
    const tempUrl = pathname.split('/index')[0];
    router.push(`${tempUrl}/addaccu`);
    // router.push('/bigwarehouse/provfundprotect/add');
  };

  // 获取大库列表
  onSearch = value => {
    const { dispatch } = this.props;
    if (value.trim().length) {
      dispatch({
        type: 'accuware/fetchBigwareList',
        payload: { accoName: value.trim() },
      });
    }
  };

  linkRoute = (id, path, accoStatus) => {
    const {
      location: { pathname },
    } = this.props;
    const tempUrl = pathname.split('/index')[0];
    return id
      ? router.push(`${tempUrl}/${path}?accuAccoId=${id}&&accoStatus=${accoStatus}`)
      : router.push(`${tempUrl}/${path}`);
  };

  updateStatus = (id, accoStatus) => {
    const { dispatch } = this.props;
    const obj = {
      accuAccoIds: id,
      accoStatus,
    };
    const title = Number(accoStatus === 2) ? '你确定要停用此大库吗？' : '你确定要启用此大库吗？';

    confirm({
      title,
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'accuware/updateStatus',
          payload: obj,
        });
        // mgrAxios('/suppAccu/updateStatus', obj)
        //   .then(res => {
        //     if (res.success == true) {
        //       message.success(warnMessage);
        //       _this.getList(_this.state.nowPage, _this.state.pageNum);
        //     } else {
        //       message.error(res.message);
        //     }
        //   })
        //   .catch(err => {});
      },

      onCancel() {},
    });
  };

  // 查询
  goSearch = () => {
    const { dispatch, form } = this.props;
    form.validateFields((err, formFieldsValue) => {
      if (err) return;
      const tempValues = {};
      Object.keys(formFieldsValue).forEach(key => {
        if (formFieldsValue[key] && formFieldsValue[key].key) {
          tempValues[key] = formFieldsValue[key].key === undefined || formFieldsValue[key].key === null
            ? null
            : formFieldsValue[key].key;
        } else {
          tempValues[key] =
          formFieldsValue[key] === undefined || formFieldsValue[key] === null
            ? null
            : formFieldsValue[key].trim();
        }
      });
      dispatch({
        type: 'accuware/updateModelData',
        payload: { formFieldsValue: tempValues },
      });
      this.getList();
    });
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist() {
    await this.resetSearch();
    await this.getList();
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
      bigwareList,
      listLoading,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="公司名称" {...this.formItemLayout}>
              {getFieldDecorator('accuUnitName', {
                initialValue: formFieldsValue.accuUnitName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="大库名称" {...this.formItemLayout}>
              {getFieldDecorator('accuAccoId', {
                initialValue: formFieldsValue.accuAccoId,
              })(
                <BigwareList
                  placeholder="请输入"
                  onSearch={this.onSearch}
                  bigwareList={bigwareList}
                  loading={listLoading}
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="账户状态" {...this.formItemLayout}>
              {getFieldDecorator('accoStatus', {
                initialValue: formFieldsValue.accoStatus,
              })(<DictCode dictType="COMMON_ENABLED_STATUS" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="执行地区" {...this.formItemLayout}>
              {getFieldDecorator('accuAreaId', {
                initialValue: formFieldsValue.accuAreaId,
              })(<Area labelInValue />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <div style={{ float: 'right', marginBottom: 24 }}>
                <Button type="primary" htmlType="submit" onClick={() => this.goSearch()}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起
                  <UpOutlined />
                </a>
              </div>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
      bigwareList,
      listLoading,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="公司名称" {...this.formItemLayout}>
              {getFieldDecorator('accuUnitName', {
                initialValue: formFieldsValue.accuUnitName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="大库名称" {...this.formItemLayout}>
              {getFieldDecorator('accuAccoId', {
                initialValue: formFieldsValue.accuAccoId,
              })(
                <BigwareList
                  placeholder="请输入"
                  onSearch={this.onSearch}
                  bigwareList={bigwareList}
                  loading={listLoading}
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={() => this.goSearch()}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const { stateMap } = this.state;
    const { loading, pageData = [], selectedRows = [], selectedRowKeys = [] } = this.props;
    const accuColumns = [
      {
        title: '大库名称',
        dataIndex: 'accoName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '公司名称',
        dataIndex: 'unitName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '地区',
        dataIndex: 'areaName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, row) => {
          let name = '';
          if (row.areaList) {
            row.areaList.map(value => {
              name += value.areaName;
            });
          }

          return name || '--';
        },
      },
      {
        title: '账户状态',
        align: 'center',
        dataIndex: 'accoStatusName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        render: (text, record) => (
          <Badge key={record.accoStatus} status={stateMap[record.accoStatus]} text={text} />
        ),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        width: 150,
        render: (text, record) => (
          <div>
            <div>
              <Authorized authority="business:suppAccu:update" noMatch={null}>
                <span
                  style={{ color: '#1890FF', cursor: 'pointer' }}
                  onClick={() => this.linkRoute(record.accuAccoId, 'editaccu', record.accoStatus)}
                >
                  {' '}
                  修改
                </span>
                <Divider type="vertical" />
              </Authorized>
              {checkPermissions('business:suppAccu:updateStatus') ? (
                <Dropdown
                  overlay={
                    <Menu>
                      <Menu.Item key="view">
                        <a onClick={() => this.linkRoute(record.accuAccoId, 'detailaccu')}> 查看</a>
                      </Menu.Item>
                      <Menu.Item
                        key="able"
                        onClick={() => this.updateStatus(record.accuAccoId, record.accoStatus)}
                      >
                        {Number(record.accoStatus) === 2 ? '停用' : '启用'}
                      </Menu.Item>
                    </Menu>
                  }
                >
                  <a>
                    更多 <DownOutlined />
                  </a>
                </Dropdown>
              ) : (
                <a
                  href="javascript:;"
                  onClick={() => this.linkRoute(record.accuAccoId, 'detailaccu')}
                >
                  {' '}
                  查看
                </a>
              )}
              {/* <Dropdown
                overlay={
                  <Menu>
                    <Menu.Item key="view">
                      <a onClick={() => this.linkRoute(record.accuAccoId, 'detailaccu')}> 查看</a>
                    </Menu.Item>
                    {checkPermissions('business:suppAccu:updateStatus') && (
                      <Menu.Item
                        key="able"
                        onClick={() => this.updateStatus(record.accuAccoId, record.accoStatus)}
                      >
                        {Number(record.accoStatus) === 2 ? '停用' : '启用'}
                      </Menu.Item>
                    )}
                  </Menu>
                }
              >
                <a>
                  更多 <Icon type="down" />
                </a>
              </Dropdown> */}
            </div>
          </div>
        ),
      },
    ];
    return (
      <div>
        <div
          className={styles.tableListForm}
          style={{
            margintop: 4,
            marginBottom: 16,
            paddingTop: 24,
            paddingRight: 24,
            backgroundColor: '#fafafa',
          }}
        >
          {this.renderForm()}
        </div>
        {(checkPermissions('business:suppAccu:insert') ||
          checkPermissions('business:suppAccu:deleteMul')) && (
          <Row style={{ marginBottom: 16 }}>
            <Authorized authority="business:suppAccu:insert" noMatch={null}>
              <Button type="primary" onClick={this.invoiceApply} style={{ marginRight: 8 }}>
                新增
              </Button>
            </Authorized>
            <Authorized authority="business:suppAccu:deleteMul" noMatch={null}>
              <Button onClick={this.deleteItem}>删除</Button>
            </Authorized>
          </Row>
        )}
        <StandardTable
          selectedRows={selectedRows}
          loading={loading}
          selectedRowKeys={selectedRowKeys}
          data={pageData}
          columns={accuColumns}
          rowKey="accuAccoId"
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
  }
}
export default AccuWare;
